package me.itsoo.elasticbatis.binding;

import lombok.extern.slf4j.Slf4j;
import me.itsoo.elasticbatis.session.SqlSession;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * MapperProxy
 *
 * @param <T> T
 * @author zhangxy4
 * @version 0.0.1
 * @since 2025/4/3
 */
@Slf4j
public class MapperProxy<T> implements InvocationHandler, Serializable {
    private static final long serialVersionUID = 8205309715074003633L;

    private final SqlSession sqlSession;
    private final Class<T> mapperInterface;
    private final Map<Method, MapperMethod> methodCache;

    public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
        this.sqlSession = sqlSession;
        this.mapperInterface = mapperInterface;
        this.methodCache = methodCache;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (Object.class.equals(method.getDeclaringClass())) {
            return method.invoke(this, args);
        }

        MapperMethod mapperMethod = this.cachedMapperMethod(method);
        return mapperMethod.execute(sqlSession, args);
    }

    private MapperMethod cachedMapperMethod(Method method) {
        return methodCache.computeIfAbsent(method, k ->
                new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()));
    }
}
